package com.ohc.itnanls;

/**
 * 超级数组
 */
public class SupperArray {

    private int[] elements;

    private int currertIndex = -1;

    private int length = 0;

    public SupperArray() {
        this(10);
    }

    public SupperArray(int capacity) {
        elements = new int[capacity];
    }

    public void addToHead(int data) {
        this.add(0, data);
    }

    public void addToTail(int data) {
        this.add(currertIndex + 1, data);
    }

    public void add(int index, int data) {
        currertIndex++;
        if (currertIndex > elements.length - 3) {
            int[] temp = new int[elements.length * 2];
            for (int i = 0; i < elements.length; i++) {
                temp[i] = elements[i];
            }
            this.elements = temp;
        }
//          移动位置，腾出空间
        for (int i = currertIndex-1; i >= index; i--) {
            elements[i + 1] = elements[i];
        }
        length++;
        elements[currertIndex] = data;
    }

    public void delete(int index) {
        if (index < 0 || index > length - 1) {
            throw new RuntimeException();
        }
        for (int i = index + 1; i < elements.length; i++) {
            elements[i - 1] = elements[i];
        }
        currertIndex--;
        length--;
    }

    public void set(int index, int data) {
        if (index < 0 || index > elements.length - 1) {
            throw new RuntimeException();
        }
        elements[index] = data;
    }

    public int select(int index) {
        if (index < 0 || index > elements.length - 1) {
            throw new RuntimeException();
        }
        return elements[index];
    }

    public int size() {
        return this.length;
    }


    public String arrayToString() {
        String result = "[";
        for (int i = 0; i < this.length; i++) {
            result += "" + elements[i] + ",";
        }
        return result.substring(0, result.length() - 1) + "]";
    }
}
